<template>
  <MainSlot v-loading="loading">
    <template v-slot:searchForm>
      <SearchForm v-if="formItemList.length" :formItemList="formItemList" :unfoldFlag="unfoldFlag" @search="search"
        @isUnfold="(v) => { unfoldFlag = v }">
      </SearchForm>
    </template>
    <template v-slot:btn>
      <BtnSlot :btnList="btnList" @handleEvent="getBtnEvent"></BtnSlot>
    </template>
    <template v-slot:table>
      <div class="putPondList">
        <div class="info" v-for="item, index in dataList" :key="index">
          <div class="title">
            <span class="name">{{ item.fishPondName || '鱼塘名称' }}</span>
          </div>
          <div class="options">
            <div class="numTotal">
              <div class="total"><span class="label">投塘总条数:</span>{{ item.totalInputNum || 0 }}尾</div>
              <div class="total"><span class="label">总投塘重量:</span>{{ item.totalInputWeight || 0 }}斤</div>
              <div class="total"><span class="label">批次编号:</span>{{ item.batchName || '--' }}</div>
            </div>
            <div class="option">
              <div class="item">
                <span class="label">是否封塘</span>
                <el-switch :disabled="item.isClosePond" v-model="item.isClosePond"
                  @change="handleClosePond(item, item.isClosePond)" :active-value="true" :inactive-value="false"
                  active-color="#13ce66" inactive-color="#ff4949">
                </el-switch>
              </div>
              <el-button class="item" type="primary" plain @click="addFishPond(item)">添加投塘</el-button>
              <el-button class="item" type="primary" plain @click="lookView(item)">投塘详细信息</el-button>
            </div>
          </div>
          <template v-if="item.batchPondList">
            <div class="dataList" v-for="info, index in item.batchPondList" :key="index + 'info'">
              <div class="data">
                <div class="row">
                  <span class="label">投塘品种：</span>
                  <span class="tag">{{ info.fishVarietyName || '--' }}</span>
                </div>
                <div class="row">
                  <span class="label">投塘尾数：</span>
                  <span class="tag">{{ info.inputNum || 0 }}条</span>
                </div>
                <div class="row">
                  <span class="label">投塘重量：</span>
                  <span class="tag">{{ info.inputWeight || 0 }}斤</span>
                </div>
                <div class="row">
                  <span class="label">在塘尾数：</span>
                  <span class="tag">{{ info.num >= 0 ? info.num : 0 }}条</span>
                </div>
                <div class="row">
                  <span class="label">转塘尾数：</span>
                  <span class="tag">{{ info.transferNum }}条</span>
                </div>
                <div class="row">
                  <span class="label">直鱼尾数：</span>
                  <span class="tag">{{ info.deadNum }}条</span>
                </div>
              </div>
            </div>
          </template>
        </div>
      </div>
    </template>
    <template v-slot:pagination>
      <Pagination @current-change="handleCurrentChange" :size="size" :page="page" :total="total">
      </Pagination>
    </template>
    <template v-slot:dialogModule>
      <AddEdit :title="'投塘'" :batchList="batchList" :fishPondList="fishPondList" :fishVarietyList="fishVarietyList"
        :specificationList="specificationList" :staffList="staffList" :weighingList=weighingList
        @closeDialog="closeDialog" :addEditFlag="addEditFlag" :dialogVisible="dialogVisible" :data="formData">
      </AddEdit>
      <DataInfo :dialogVisible="dialogVisible_lookView" :data="lookViewData" @closeDialog="closeDataInfoDialog">
      </DataInfo>
    </template>
  </MainSlot>
</template>
<script>
import MainSlot from "@/components-production-management/MainSlot";
import Pagination from '@/components-production-management/Pagination';
import SearchForm from '@/components-production-management/SearchForm';
import TableData from '@/components-production-management/TableData';
import BtnSlot from '@/components-production-management/BtnSlot';
import EnumSlot from '@/components-production-management/EnumSlot';
import AddEdit from './components/addEdit.vue';
import DataInfo from './components/dataInfo.vue';

//批次
import batchManagement from '@/api/production-management/batch-management.js';
//鱼塘
import fishPondApi from "@/api/basic-info-manage/fishPond";
//称重接口
import weighingManagement from '@/api/production-management/weighing-management.js';
//品种
import fishVarietyApi from "@/api/basic-info-manage/fishVariety"
//规格
import specificationApi from "@/api/basic-info-manage/specification/index";
//获取员工
import staffApi from "@/api/basic-info-manage/staff";
//投塘
import pondStockingManagement from '@/api/production-management/pond-stocking-management.js';
export default {
  components: { MainSlot, Pagination, SearchForm, TableData, BtnSlot, EnumSlot, AddEdit, DataInfo },
  data() {
    return {
      value: false,
      unfoldFlag: false,
      loading: false,
      dialogVisible: false,
      dialogVisible_lookView: false,
      addEditFlag: 'add',
      selectList: [],
      formData: {},
      page: 1,
      size: 5,
      total: 10,
      selectIndex: 0,
      searchFormData: {},
      btnList: ['add'],
      dataList: [],
      lookViewData: {},
      formItemList: [
        {
          label: '养殖鱼塘',
          type: 'select',
          selectOptions: [],
          param: 'fishPondId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
        {
          label: '养殖品种',
          type: 'select',
          selectOptions: [],
          param: 'fishVarietyId',
          defaultSelect: '', // 下拉框默认选中项
          multiple: false,
          isShow: true
        },
      ],
      fishPondList: [],
      batchList: [],
      staffList: [],
      specificationList: [],
      fishVarietyList: [],
      weighingList: []
    }
  },
  mounted() {
    this.queryPageByCondition();
    this.initData();
  },
  methods: {
    //初始化数据
    async initData() {
      let { data: fishPondList } = await fishPondApi.queryByCondition({ bindBatch: true });//查询鱼塘列表
      let { data: batchList } = await batchManagement.queryByCondition({ unCompleteBatch: true });//查询批次列表
      let { data: fishVarietyList } = await fishVarietyApi.queryByCondition();//查询品种
      let { data: specificationList } = await specificationApi.queryByCondition();//查询规格
      let { data: staffList } = await staffApi.queryByCondition();
      let { data: weighingList } = await weighingManagement.queryByCondition();

      this.fishPondList = fishPondList || [];
      this.batchList = batchList || [];
      this.fishVarietyList = fishVarietyList || [];
      this.specificationList = specificationList || [];
      this.staffList = staffList || [];
      this.weighingList = weighingList || [];
      this.setFormOptions();
    },
    setFormOptions() {
      let list = JSON.parse(JSON.stringify(this.formItemList));
      this.formItemList = []
      list.forEach((item, index) => {
        if (item.param.indexOf('fishPondId') !== -1) {
          let selectOptions = this.fishPondList.map(data => {
            return {
              text: data.pondName, value: data.fishPondId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
        if (item.param.indexOf('fishVarietyId') !== -1) {
          let selectOptions = this.fishVarietyList.map(data => {
            return {
              text: data.varietyName, value: data.fishVarietyId
            }
          })
          item.defaultSelect = this.searchFormData[item.param];
          item.selectOptions = selectOptions;
        };
      });

      this.$nextTick(() => {
        this.$set(this, 'formItemList', list)
        console.log(this.formItemList)
      })
    },
    addFishPond(row) {
      this.formData = JSON.parse(JSON.stringify(
        {
          batchId: row.batchId,
          batchName: row.batchName,
          fishPondId: row.fishPondId,
          fishPondName: row.fishPondName
        }
      ))
      this.addEditFlag = 'add';
      this.dialogVisible = true;
    },

    //查询
    queryPageByCondition() {
      let params = {
        page: this.page,
        size: this.size,
        entity: {
          ...this.searchFormData
        }
      }
      this.loading = true;
      pondStockingManagement.queryPageForInputPondHome(params).then(res => {
        this.loading = false;
        if (res.success == 1) {
          this.dataList = res.data.content || [];
          this.dataList.forEach((item, index) => {
            this.$set(this.dataList, index, {
              ...item,
              isClosePond: !!item.closePondDate
            });
          })
          this.total = res.data.totalElements;
          if (res.data.totalPages && this.page > res.data.totalPages) {
            this.page = res.data.totalPages;
            this.queryPageByCondition();
          }
        } else {
          this.loading = true;
          this.$message.warning(res.message || '分页查询失败')
        }
      }).catch(err => {
        console.log(err)
      })
    },
    handleClosePond(row, flag) {
      console.log(row.batchPondList)
      if (row.batchPondList && row.batchPondList.length > 0) {
        this.$confirm('封塘操作不可逆, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          let { success } = await pondStockingManagement.closePond(row.batchId);
          success && this.$message.success('操作成功');
          !success && this.$message.warning('操作失败');
        }).catch(() => {
          row.isClosePond = false;
          this.$message({
            type: 'info',
            message: '已删除'
          });
        });
      } else {
        row.isClosePond = false;
        this.$message.warning('该鱼塘还未投塘请投塘后再封塘！')
      }

    },
    //搜索
    search(data) {
      this.page = 1;
      this.searchFormData = { ...this.searchFormData, ...data };
      this.queryPageByCondition();
    },
    //翻页查询
    handleCurrentChange(page) {
      this.page = page;
      this.queryPageByCondition();
    },
    //查看详情
    lookView(row) {
      this.lookViewData = JSON.parse(JSON.stringify(row));
      this.dialogVisible_lookView = true;
    },
    // 多选方法
    selectionChange(val) {
      this.selectList = val || []
    },
    //获取选中Btn
    getBtnEvent(flag) {
      console.log(flag)
      if (flag == 'add') {
        this.dialogVisible = true
      }
      this.addEditFlag = flag
    },
    closeDataInfoDialog() {
      this.dialogVisible_lookView = false;
      this.lookViewData = {};
      this.queryPageByCondition();
    },
    //关闭弹窗
    closeDialog() {
      this.dialogVisible = false;
      this.formData = {};
      this.initData();
      this.queryPageByCondition();
    },
  }
};
</script>
<style lang="scss" scoped>
.putPondList {
  width: 100%;
  height: 100%;
  overflow: auto;
  background: #ffffff;

  .title {
    width: 100%;
    padding: 0 15px;
    background: #4b8bc9;
    line-height: 40px;
    font-size: 14px;
    color: #ffffff;
  }

  .options {
    height: 40px;
    padding: 0 15px;
    background: #dbf0f9;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .label {
      color: #4b8bc9;
    }

    .numTotal {
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .total {
        margin-right: 15px;
        color: #666666;
      }
    }

    .option {
      display: flex;
      justify-content: flex-end;
      align-items: center;

      .item {
        margin-left: 15px;

        .label {
          margin-right: 10px;
          color: #4b8bc9;
        }
      }
    }
  }

  .dataList {
    width: 100%;
    padding: 0 15px;
    background-color: #f8feff;
    transition: all 0.5s;
    cursor: pointer;

    &:hover {
      transform: translateX(-2px);
      background-color: #e9f2f3;
    }

    .data {
      height: 40px;
      display: flex;
      align-items: center;
      justify-content: flex-start;
      flex-wrap: nowrap;
      text-align: left;
      color: #666666;
      border-bottom: 1px solid #dfdfdf;

      .row {
        width: calc(100% / 5);

        .label {
          color: #4b8bc9;
        }
      }
    }
  }
}
</style>